import 'dart:developer';

import 'package:charset_converter/charset_converter.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shen_nai/app/user_controller.dart';
import 'package:shen_nai/routes/app_routes.dart';
import 'package:shen_nai/socket/socket_server_manage.dart';

//欢迎页
class WelcomePage extends StatefulWidget {
  const WelcomePage({Key? key}) : super(key: key);

  @override
  State<WelcomePage> createState() => _WelcomePageState();
}

class _WelcomePageState extends State<WelcomePage> {
  @override
  void initState() {
    super.initState();
    //1秒后 判断是否需要登录
    Future.delayed(const Duration(milliseconds: 1000), () async {
      if (Get.find<UserController>().account.isNotEmpty &&
          Get.find<UserController>().password.isNotEmpty) {
        _login();
      } else {
        Get.offAllNamed(AppRoute.LOGIN);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold();
  }

  //登录
  _login() {
    SocketServerManage().writeData(
        'login ${Get.find<UserController>().account} ${Get.find<UserController>().password}',
        (data) {
      log('welcome: ${String.fromCharCodes(data)}');
      CharsetConverter.decode('GBK', data).then((value) {
        if (value.contains('sucessed')) {
          Get.offAllNamed(AppRoute.HOME);
        } else if (value.contains('alread')) {
          Get.offAllNamed(AppRoute.HOME);
        } else {
          Get.off(AppRoute.LOGIN);
        }
      }, onError: (e) {
        log(e.toString());
      });
    });
  }
}
